<!doctype html>
<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>聊天室</title>
  <link rel="stylesheet" href="/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/layout.css">
</head>

<body>

  <div class="container">
    <h1>express + socket.io 聊天室</h1>
    <div class="row" id="login">
      <div class="col-md-12">
        <div class="form-group">
          <label for="username">姓名</label>
          <input class="form-control" id="username" placeholder="姓名昵称">
        </div>
        <button class="btn btn-default" id="show-btn">提交</button>
      </div>
    </div>

    <div class="row" id="content">
      <div class="col-md-12" id="msg">
        
      </div>
      <div class="col-md-12">
        <textarea class="form-control" rows="3" id="megcon"></textarea>
        <button class="btn btn-success" id="send-btn">提交</button>
      </div>
    </div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="/js/bootstrap.min.js"></script>

  <script src="/socket.io.js"></script>
  <script>
    //创建模板
    function createTpl(data) {
      return `
        <div class="con-item">
          <p>
            <span class="label label-info">${username == data.username ? '我' : data.username}</span>
          </p>
          <p>
            <span class="alert alert-${username == data.username ? 'success' : 'warning'}">
              ${data.msg}
            </span>
          </p>
        </div>
      `
    }

    let socket
    let username
    //显示聊天
    $('#show-btn').on('click', () => {
      username = $.trim($('#username').val())
      if (username == '') return

      $('#login').hide()
      $('#content').show()

      //建立连接
      socket = io('ws://localhost:3000')
      //监听服务端的事件推送
      socket.on('connect', () => {
        //当连接成功时候  发送消息
        socket.emit('login', username)
      })
      socket.on('disconnect', () => {
        console.log('断开连接')
      })

      //接收服务端消息 显示出来
      socket.on('msg', data => {
        $('#msg').append(createTpl(data))
      })
    })

    //点击提交  发送消息到服务端
    $('#send-btn').on('click', () => {
      socket.emit('send', $('#megcon').val())
      $('#megcon').val('')
    })
  </script>
</body>

</html>